//
//  LGMessageRecordManager.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2025/6/30.
//

#import "LGMessageRecordManager.h"
#import <AVFAudio/AVFAudio.h>

@interface LGMessageRecordManager()<AVAudioPlayerDelegate>
/**   */
@property (nonatomic , strong)LGVoiceMessageCell *voiceCell;
/**   */
@property (nonatomic , strong)AVAudioPlayer *audioPlayer;
/**  语音是否在被下载 */
@property (nonatomic , assign)BOOL voiceDownload;
/**  正在播放语音 */
@property (nonatomic , assign)BOOL voicePlaying;

@end

@implementation LGMessageRecordManager

+ (instancetype)sharedManager{
    static LGMessageRecordManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[LGMessageRecordManager alloc] init];
    });
    return _sharedManager;
}


- (void)playVoiceMessage:(NSDictionary *)voiceData cell:(LGVoiceMessageCell *)currentCell{
    if (self.voicePlaying) {
        [self stopVoiceMessage];
        if (self.voiceCell == currentCell) return;
    }
    self.voiceCell = currentCell;
    self.voicePlaying = YES;
    BOOL isExist = NO;
    NSString *voiceUrl = LGNSString(voiceData[@"content"][@"url"]);
    NSString *path = [self getVoicePath:voiceUrl isExist:&isExist];
    if(isExist) {
        [self playInternal:path];
        [self.voiceCell.voiceView startAnimating];
    } else {
        if(self.voiceDownload) {
            return;
        }
        //网络下载
        self.voiceDownload = YES;
        @weakify(self)
        [RequestUtil downloadVoice:path url:voiceUrl success:^(NSURL *filePath) {
            @strongify(self)
            self.voiceDownload = NO;
            [self playInternal:path];
            [self.voiceCell.voiceView startAnimating];
        } failure:^(NSError *error) {
            @strongify(self)
            self.voiceDownload= NO;
            [self stopVoiceMessage];
        }];
    }
}

- (void)playInternal:(NSString *)path{
    if (!self.voicePlaying)
        return;
    //play current
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    self.audioPlayer.delegate = self;
    bool result = [self.audioPlayer play];
    if (!result) {
//        self.wavPath = [[path stringByDeletingPathExtension] stringByAppendingString:@".m4a"];
//        [EMVoiceConverter amrToWav:path wavSavePath:self.wavPath];
//        NSURL *url = [NSURL fileURLWithPath:self.wavPath];
        [self.audioPlayer stop];
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        self.audioPlayer.delegate = self;
        [self.audioPlayer play];
    }
}

- (void)stopVoiceMessage{
    if ([self.audioPlayer isPlaying]) {
        [self.audioPlayer stop];
        self.audioPlayer = nil;
    }
    self.voicePlaying = NO;
    [self.voiceCell.voiceView stopAnimating];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;{
    self.voicePlaying = NO;
    [self.voiceCell.voiceView stopAnimating];
}

- (NSString *)getVoicePath:(NSString *)voiceUrl isExist:(BOOL *)isExist{
//    NSString *path = nil;
    BOOL isDir = false;
    *isExist = NO;
    NSArray *tempArray = [voiceUrl componentsSeparatedByString:@"/"];
    NSString *fileName = LGNSString([tempArray lastObject]);
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 判断文件夹是否存在
    __block NSString *documentPath = [path stringByAppendingPathComponent:@"/Documents/message/voice/"];
    if(![[[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentPath error:nil] count]){
        [[NSFileManager defaultManager] createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    __block NSString *filePath = [documentPath stringByAppendingPathComponent:fileName];
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir]){
        if(!isDir){
            *isExist = YES;
        }
    }
    return filePath;
}


//查看图片大图
- (void)showImageMessage:(NSDictionary *)voiceData{
    
}

//播放视频
- (void)showVideoMessage:(NSDictionary *)voiceData{
    
}
@end
